<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
use think\Exception;
use think\exception\ErrorException;

class Selforder extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }
    /**
     * getAttrById
     * 为老汤
     */
    public function getAttrById()
    {
        extract(input());
        $data = Db::table('up_self_goods_attr')
            ->where('sign_id',$attr_id)
            ->where('goods_id',$good_id)
            ->where('is_delete',0)
            ->find();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * getAttrById
     * 为老汤
     */
    public function getAttrByIdFor()
    {
        extract(input());
        $data = Db::table('up_goods')
            ->where('good_id',$good_id)
            ->find();
        $data['sign_str'] = $data['good_color'] . '/' . 1000;
        return json(['status'=>200,'msg'=>1000]);
    }
    /**
     * myOrderNums
     * 我的页面的订单数量
     * contract：1是自营  2是增补
     */
    public function myOrderNums()
    {
        extract(input());
        $data = $this->formyOrderNums($user_id,1);
        $data2 = $this->formyOrderNums($user_id,2);
        return json(['status'=>200,'msg'=>$data,'msg2'=>$data2]);
    }
    /**
     * myOrderNums
     * 我的页面的订单数量
     * contract：1是自营  2是增补
     */
    public function formyOrderNums($user_id,$contract)
    {
        extract(input());
        $where = [
            'user_id' => $user_id,
            'order_contract' => $contract,
            'o.is_delete' => 0
        ];
        if($contract != 1){
            $can = $this->getSonByUser($user_id);
            if($can['status'] != 200){
                return json($can);
            }
            $sondata = $can['msg'];
            $where = [
                'order_user_son_id' => $sondata['uson_id'],
                'order_contract' => $contract,
                'o.is_delete' => 0
            ];
        }
        $where1 = [ //待付款
            'is_pay' => 0,
        ];
        $where2 = [ //待发货
            'is_pay' => 1,
            'is_send' => 0
        ];
        $where3 = [ //待收货
            'is_pay' => 1,
            'is_send' => 1
        ];
        $where4 = [ //待评价
            'is_pay' => 1,
            'is_send' => 2,
            'sale_status' => 0,
        ];
        $data = array();
        $data['nopay'] = Db::table('up_self_order')
            ->where($where)
            ->where($where1)
            ->count();
        $data['nosend'] = Db::table('up_self_order')
            ->where($where)
            ->where($where2)
            ->count();
        $data['noget'] = Db::table('up_self_order')
            ->where($where)
            ->where($where3)
            ->count();
        $data['nocomment'] = Db::table('up_self_order')
            ->where($where)
            ->where($where4)
            ->count();

        return $data;
    }
    /**
     * 我的订单
     * type：1待付款 2是待发货 3是待收货 4是已收货待评价 5是已完成
     * contract：1是自营  2是增补  3是统购
     */
    public function myOrders()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $where = [
            'user_id' => $user_id,
            'order_contract' => $contract,
            'o.is_delete' => 0
        ];
        if(!isset($contract)){
            $contract = 1;
        }
        $good_table = 'up_self_goods';
        if($contract != 1){
            $can = $this->getSonByUser($user_id);
            if($can['status'] != 200){
                return json($can);
            }
            $sondata = $can['msg'];
            $where = [
                'order_user_son_id' => $sondata['uson_id'],
                'order_contract' => $contract,
                'o.is_delete' => 0
            ];
            $good_table = 'up_goods';
        }
        if(isset($type) && $type){
            if($type == 1){
                $where['is_pay'] = 0;
            }else{
                $where['is_pay'] = 1;
                if($type == 2){
                    $where['is_send'] = 0;
                }
                if($type == 3){
                    $where['is_send'] = 1;
                }
                if($type == 4){
                    $where['is_send'] = 2;
                    if($contract != 3){
                        $where['sale_status'] = 0;
                    }
                }
                if($type == 5){
                    $where['is_send'] = 3;
                }
            }
        }
        //-----统购订单的特殊性
        if($contract == 3){
            $where['is_pay'] = 1;
        }
        $field = 'o.order_id,o.is_sale,order_no,total_price,is_pay,is_send,sale_status,tui_status,order_cancel_status';
        $field .= ',o.order_erp_year,o.pay_time,o.order_contract,o.order_ts_id,s.school_name_remark school_name';
        $order = Db::table('up_self_order')->alias('o')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
//            ->join('up_self_goods g','od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->order('o.created_at desc')
            ->page($page,10)
            ->field($field)
            ->select();
        if($order){
            foreach ($order as $k=>$v){
                $order[$k]['send_name'] = $this->getSendName($v['order_contract'],$v['is_pay'],$v['is_send'],$v['pay_time']);
                if($contract == 3){
                    $details = Db::table('up_self_order_detail')
                        ->where('order_id',$v['order_id'])
                        ->group('tg_type')
                        ->field('tg_type,sum(num) num')
                        ->select();
                    $order[$k]['goods'] = $details;
                }else{
                    $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,detail_id';
                    $details = Db::table('up_self_order_detail')->alias('od')
                        ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                        ->where('order_id',$v['order_id'])
                        ->field($field)
                        ->select();
                    $order[$k]['goods'] = $details;
                    $order[$k]['count_num'] = count($details);
                }

            }
        }
        return json(['status'=>200,'msg'=>$order]);
    }
    public function myOrdersNew()
    {
        extract(input());
//        $user_id=1;$page=1;$type=1;
        $today = date('Y-m-d H:i:s');
        $where1 = [
            'user_id' => $user_id,
            'order_contract' => 1,
            'o.is_delete' => 0
        ];
        //------------------------------------------------------------------------
//        $can = $this->getSonByUser($user_id);
//        if($can['status'] != 200){
//            return json($can);
//        }
//        $sondata = $can['msg'];
        $where2 = [
//            'order_user_son_id' => $sondata['uson_id'],
            'user_id' => $user_id,
            'order_contract' => 2,
            'o.is_delete' => 0
        ];
        $where3 = [
//            'order_user_son_id' => $sondata['uson_id'],
            'user_id' => $user_id,
            'order_contract' => 3,
            'is_pay' => 1, //-----统购订单的特殊性
            'o.is_delete' => 0
        ];
        //------------------------------------------------------------------------
        $where = [];
        if(isset($type) && $type){
            if($type == 1){
                $where['is_pay'] = 0;
                $where3['order_id'] = ['<',0];
            }else{
                $where['is_pay'] = 1;
                if($type == 2){
                    $where['is_send'] = 0;
                }
                if($type == 3){
                    $where['is_send'] = 1;
                }
                if($type == 4){
                    $where['is_send'] = 2;
                    $where1['sale_status'] = 0; //
                    $where2['sale_status'] = 0; //
                }
                if($type == 5){
                    $where['is_send'] = 3;
                }
            }
        }
        if($where){
            $where1 = array_merge($where1,$where);
            $where2 = array_merge($where2,$where);
            $where3 = array_merge($where3,$where);
        }
//        dump($where3);die;
        $field = 'o.order_push_erp,o.order_id,o.order_contract,o.is_sale,order_no,total_price,is_pay,is_send,sale_status,tui_status,order_cancel_status';
        $field .= ',o.order_erp_year,o.order_ts_id,s.school_name_remark school_name';
        $field .= ',o.order_user_son_id,o.pay_time,o.order_cancel_pay,o.auto_cancel';
        $order = Db::table('up_self_order')->alias('o')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
//            ->join('up_self_goods g','od.goods_id=g.good_id','LEFT')
            ->where(function ($query) use ($where1) {
                $query->where($where1);
            })
            ->whereOr(function ($query) use ($where2) {
                $query->where($where2);
            })
            ->whereOr(function ($query) use ($where3) {
                $query->where($where3);
            })
            ->order('o.created_at desc')
            ->page($page,10)
            ->field($field)
            ->select();
        if($order){
            foreach ($order as $k=>$v){
//                $order[$k]['sale_status'] = 0; //列表不显示售后状态了
                $order[$k]['send_name'] = $this->getSendName($v['order_contract'],$v['is_pay'],$v['is_send'],$v['pay_time']);
                if($v['order_contract'] == 3){
                    $details = Db::table('up_self_order_detail')
                        ->where('order_id',$v['order_id'])
                        ->group('tg_type')
                        ->field('tg_type,sum(num) num')
                        ->select();
                    $order[$k]['goods'] = $details;
                }else{
                    $good_table = 'up_self_goods';
                    if($v['order_contract'] != 1) $good_table = 'up_goods';

                    $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,detail_id,detail_express,detail_express_no';
                    $details = Db::table('up_self_order_detail')->alias('od')
                        ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                        ->where('order_id',$v['order_id'])
                        ->field($field)
                        ->select();
                    //----------判断有没有全部发货-start----
                    $mwwWlFlag = 1;
                    $mwwWlName = '';
                    $mwwWl = '';
                    $order[$k]['send2'] = 1; //只能这么去做确认收货的判断，否则会影响售后的功能
                    foreach ($details as $kkk => $vvv){
                        if($vvv['detail_express_no'] && $mwwWl == ''){
                            $mwwWl = $vvv['detail_express_no'];
                            $mwwWlName = $vvv['detail_express'];
                        }
                        if($vvv['detail_express_no'] && $mwwWl){
                            if($mwwWl != $vvv['detail_express_no']) $mwwWlFlag = 2;
                        }
                        //-------------------
                        if(!$vvv['detail_express_no'] && $order[$k]['is_send'] == 1) $order[$k]['send2'] = 2;
                    }
                    if($mwwWl == '') $mwwWlFlag = 2;
                    $order[$k]['mwwWlFlag'] = $mwwWlFlag;
                    $order[$k]['mwwWl'] = $mwwWl;
                    $order[$k]['mwwWlName'] = $mwwWlName;
                    //----------判断有没有全部发货--end-----
                    $order[$k]['goods'] = $details;
                    $order[$k]['count_num'] = count($details);
                }
                $order[$k]['sonName'] = '';
                if($v['order_contract'] != 1 && $v['order_user_son_id']) {
                    $order[$k]['sonName'] = Db::table('up_u_user_son')
                        ->where('uson_id',$v['order_user_son_id'])
                        ->value('uson_username');
                }
            }
        }
        return json(['status'=>200,'msg'=>$order]);
    }
    /**
     * 我的某一个订单详情
     */
    public function myOrderInfo()
    {
        extract(input());
//        $order_id=650574;$user_id=123279;
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
//        if($order['order_contract'] == 1) $order['sale_status'] = 0; //自营的先不限制，都展示出申请售后按钮来
        $order['sale_status'] = 0; //先不限制，都展示出申请售后按钮来
        $order['send_name'] = $this->getSendName($order['order_contract'],$order['is_pay'],$order['is_send'],$order['pay_time']);
        $where = [
            'od.order_id' => $order_id
        ];
        if(isset($tui) && $tui == 1){ //孙总说没有传过这个参（孙富娟）
//            $where['th_status'] = 0; //未售后的，售后结束的不能再次售后
            if ($order['admin_tui'] != 1 && $order['admin_tui'] != 4) {
                return json(['status' => 0, 'msg' => '此订单已结束，不允许售后']);
            }
        }
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status,detail_id,detail_express,detail_express_no';
        $field .= ',t.merchant_express,t.merchant_express_no,t.express_no,t.erp_new_size';
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
            $field .= ',good_color';
//            $field .= ',good_90,good_100,good_110,good_120,good_130,good_140,good_150,good_155,good_160,good_165,good_170,good_175,good_180,good_185,good_190,good_195,good_200';
        }
        $field .= ',status,t.is_delete,t.order_erp_wl_no';
        //-----------单独判断能不能改尺码--start-----
        $edit_size = 0;
        $sondata = [];
        if($order['order_contract'] == 2){
            $can = $this->getSonByUser($user_id,$order['order_user_son_id']);
            if($can['status'] != 200){
                return json($can);
            }
            $sondata = $can['msg'];
            $time = time();
            $hours = Db::table('up_about')->where('id',9)->value('content');
//            $hours = (int)$hours;
            $pay_time_24 = strtotime($order['pay_time']) + 3600*$hours;
            if($order['is_pay'] == 1 && $order['is_send'] == 0 && $order['order_cancel_status'] <= 2 && $order['order_push_erp'] == 1 && $pay_time_24 >= $time){
                $edit_size = 1;
            }
        }
//-----------单独判断能不能改尺码--end-----
        //----------------------先排查一下老用户的goods_id问题----------------------------
        $details = Db::table('up_self_order_detail')->alias('od')
            ->where($where)
            ->field('cloth_code,goods_id,detail_id,detail_express_no')
            ->select();
        $order['send2'] = 1;
        foreach ($details as $k => $v){
            if(!$v['detail_express_no'] && $order['is_send'] == 1) $order['send2'] = 2;
            if($v['goods_id'] <= 0){
                $newgoodcode = Db::table('up_z_new_old_img')->where('old',$v['cloth_code'])->value('new');
                $changegoods_id = Db::table('up_goods')->where('good_coding',$newgoodcode)->value('good_id');
                if($changegoods_id){
                    Db::table('up_self_order_detail')->alias('od')
                        ->where('detail_id',$v['detail_id'])
                        ->setField('goods_id',$changegoods_id);
                }
            }
        }
        //--------------------------------------------------
        $detailsold = Db::table('up_self_order_detail')->alias('od')
            ->join("up_self_order_tui t",'od.detail_id=t.order_detail_id','LEFT')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->field($field)
            ->group('od.detail_id')
            ->select();
        $mwwWlFlag = 1;
        $seeSq = 1;
        $mwwWl = '';
        $mwwWlName = '';
        $details = [];
        foreach ($detailsold as $k => $v){
            if($v['detail_express_no'] && $mwwWl == ''){
                $mwwWl = $v['detail_express_no'];
                $mwwWlName = $v['detail_express'];
            }
            if($v['detail_express_no'] && $mwwWl){
                if($mwwWl != $v['detail_express_no']) $mwwWlFlag = 2;
            }
//            if($v['status'] && $v['is_delete'] == 1) { //没看懂为什么要删掉
//                unset($detailsold[$k]);
//            }else{
//                if(!$v['detail_express_no']) $v['detail_express_no'] = '';
//                $details[] = $v;
//            }
            if(!$v['detail_express_no']) $v['detail_express_no'] = '';
            $details[] = $v;
            //显示查看售后的按钮
            if($v['order_erp_wl_no']) $seeSq = 2;
        }
        if($mwwWl == '') $mwwWlFlag = 2;
//        dump($details);die;
        $wldata = [];
        if($mwwWlFlag == 1){
            $wldata = orderWuLiu($mwwWl);
            if($wldata['status'] == 200){
                $wldata['time'] = $wldata['msg'][0]['time'];
                $wldata['msg'] = $wldata['msg'][0]['context'];
            }
        }
        $topMsg = '您可在发货前修改您的尺码';
        //---------------------------------------------------------------------------
        $sadsid = ['511352','515201','533052','534877','547768','555176','556139','558039','558893','561203','561988','564555','564807','565004','565090','567227','568308','569193','570488','570620','570719','570750','571771','572540','572576','572862','573474','573570','573700','573797','573866','573961','574108','574148','574158','574236','574771','574820','574895','575003','575130','575560','575586','575868','575901','576402','577176','577430','578025','578376','578545','578672','579087','579096','579346','579473','579636','579862','579888','580515','580968','581799'];
        $panson_error = 1;
        $panson_error_address = [];
        if(in_array($order_id,$sadsid) && $order['panson_error'] == 1) {
            $panson_error = 2;
            $aid = $order['order_contract'] == 2 ? 5 : 17;
            $panson_error_address = Db::table('up_about')
                ->where('id',$aid)
                ->find();
        }
        //---------------------------------------------------------------------------
        if($order['created_at'] <= '2022-11-08 23:59:59' && $order['is_sale'] == 0) $order['is_sale'] = 1;
        return json(['status'=>200,'msg'=>$order,'goods'=>$details,'count_num' => count($details),'sondata' => $sondata
            ,'edit_size' => $edit_size,'wldata' => $wldata,'topMsg' => $topMsg
            ,'panson_error' => $panson_error,'panson_error_address' => $panson_error_address
            ,'mwwWlFlag' => $mwwWlFlag,'mwwWl' => $mwwWl,'mwwWlName' => $mwwWlName,'seeSq' => $seeSq
        ]);
    }

    /**
     * 专门获取可以售后的数据（只返回可以售后的衣服，就是info里tui的参）
     */
    public function getInfoForSale(){
        extract(input());
        if(!isset($order_erp_wl_no)) $order_erp_wl_no = '';
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        if ($order['is_send'] < 1 || $order['is_pay'] != 1 || $order['order_cancel_status'] > 2) {
            return json(['status'=>200,'msg'=>$order,'goods'=>[]]);
        }
        $where = [
            'od.order_id' => $order_id
        ];
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status,detail_id,detail_express,detail_express_no';
        $field .= ',t.merchant_express,t.merchant_express_no,t.express_no,t.erp_new_size,t.type';
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
            $field .= ',good_color';
        }
        $field .= ',status,t.is_delete';
        //先不group，判断完完再group
        $detailsold = Db::table('up_self_order_detail')->alias('od')
            ->join("up_self_order_tui t",'od.detail_id=t.order_detail_id','LEFT')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->field($field)
            ->select();
        $del = [];
        foreach ($detailsold as $k => $v){
            //只要是待审核的一律不展示
            if($v['status'] == 1) $del[] = $v['detail_id'];
//            //已同意的商家还没有发货的一律不展示：换货
//            if($v['status'] == 2 && $v['type'] == 1 && !$v['merchant_express_no']) $del[] = $v['detail_id'];
//            //已同意的退货的不展示
            if($v['status'] == 2 && $v['type'] == 2) $del[] = $v['detail_id'];
            //只要同意过，说明有售后，直接去售后列表那里申请
            if(!$order_erp_wl_no && $v['status'] == 2) $del[] = $v['detail_id'];
            if($order_erp_wl_no){
                $fuck = Db::table('up_self_order_tui')
                    ->where('order_detail_id',$v['detail_id'])
                    ->where('type',1)
                    ->where('status','in','1,2')
                    ->order('created_at desc')
                    ->field('order_erp_wl_no')
                    ->find();
                if(!$fuck) $del[] = $v['detail_id'];
                if($fuck && $fuck['order_erp_wl_no'] != $order_erp_wl_no){ //如果没有的话不会进来
                    $del[] = $v['detail_id'];
                }
            }
        }
        if($del){
            $where['od.detail_id'] = ['not in',$del];
        }
        $detailsold = Db::table('up_self_order_detail')->alias('od')
            ->join("up_self_order_tui t",'od.detail_id=t.order_detail_id','LEFT')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->field($field)
            ->group('od.detail_id')
            ->select();
        if($detailsold){
            foreach ($detailsold as $k222 => $v222){
                $lastR = $this->getLastInfo($v222['detail_id']);
                if($order['order_contract'] == 1){
                    $detailsold[$k222]['goods_info'] = $lastR['erp_new_size'];
                }else{
                    $detailsold[$k222]['goods_info'] = $v222['good_name'] . '/' . $v222['good_color'] . '/' . $lastR['erp_new_size'];
                }
            }
        }
        return json(['status'=>200,'msg'=>$order,'goods'=>$detailsold]);
    }
    /**
     * 专门获取售后列表
     */
    public function getSaleOrders(){
        extract(input());
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        $where = [
            'od.order_id' => $order_id,
            't.tui_id' => ['>',0]
        ];
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status,detail_id,detail_express,detail_express_no';
        $field .= ',t.merchant_express,t.merchant_express_no,t.express_no,t.type,t.tui_type';
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
            $field .= ',good_color';
        }
        $field .= ',status,t.is_delete';
        $field .= ',t.erp_huan_uninumber,t.erp_old_size,t.erp_new_size,t.tui_sure_get,t.tui_user_get,t.tui_master_status';
        $tuis = Db::table('up_self_order_tui')
            ->where('order_id',$order_id)
            ->where('is_delete',0)
            ->field('order_erp_wl_no')
            ->group('order_erp_wl_no')
            ->select();
        if($tuis){
            foreach ($tuis as $k => $v){
                $where['order_erp_wl_no'] = $v['order_erp_wl_no'];
                $detailsold = Db::table('up_self_order_tui')->alias('t')
                    ->join("up_self_order_detail od",'t.order_detail_id=od.detail_id','LEFT')
                    ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                    ->where($where)
                    ->field($field)
                    ->select();
                foreach ($detailsold as $k2 => $v2){
                    if($v2['type'] == 1){
                        $shouldField = 'erp_old_size';
                        $fieldfield = 'attr_id';
                        if($v2['tui_type'] == 1) $fieldfield = 'goods_info';
                        if(!$detailsold[$k2]['erp_old_size']) $detailsold[$k2]['erp_old_size'] = $v2[$fieldfield];
                    }else{
                        $shouldField = 'erp_new_size';
                        $lastR = $this->getLastInfo($v2['detail_id']);
                        $detailsold[$k2]['erp_old_size'] = $lastR['erp_old_size'];
                        $detailsold[$k2]['erp_new_size'] = $lastR['erp_new_size'];
                    }
                    if($order['order_contract'] == 1){
                        $detailsold[$k2]['goods_info_new'] = $detailsold[$k2][$shouldField];
                    }else{
                        $detailsold[$k2]['goods_info_new'] = $v2['good_name'] . '/' . $v2['good_color'] . '/' . $detailsold[$k2][$shouldField];
                    }

                }
                $tuis[$k]['infos'] = $detailsold;
            }
        }
        return json(['status'=>200,'msg'=>$tuis]);
    }
    /**
     * 专门获取售后详情
     */
    public function getSaleOrderInfo(){
        extract(input());
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        $where = [
            't.order_id' => $order_id,
            't.order_erp_wl_no' => $order_erp_wl_no
        ];
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status,detail_id,detail_express,detail_express_no';
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
            $field .= ',good_color';
        }
        $field .= ',t.*';
        $detailsold = Db::table('up_self_order_tui')->alias('t')
            ->join("up_self_order_detail od",'t.order_detail_id=od.detail_id','LEFT')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->field($field)
            ->select();
        $send2 = 1;
        $mwwWlFlag = 1;
        $mwwWl = '';
        $mwwWlName = '';
        foreach ($detailsold as $k2 => $v2){
            if($v2['type'] == 1){
                $shouldField = 'erp_old_size';
                $fieldfield = 'attr_id';
                if($v2['tui_type'] == 1) $fieldfield = 'goods_info';
                if(!$detailsold[$k2]['erp_old_size']) $detailsold[$k2]['erp_old_size'] = $v2[$fieldfield];
            }else{
                $shouldField = 'erp_new_size';
                $lastR = $this->getLastInfo($v2['detail_id']);
                $detailsold[$k2]['erp_old_size'] = $lastR['erp_old_size'];
                $detailsold[$k2]['erp_new_size'] = $lastR['erp_new_size'];
            }
            if($order['order_contract'] == 1){
                $detailsold[$k2]['goods_info_new'] = $detailsold[$k2][$shouldField];
            }else{
                $detailsold[$k2]['goods_info_new'] = $v2['good_name'] . '/' . $v2['good_color'] . '/' . $detailsold[$k2][$shouldField];
            }
            //
            if($v2['merchant_express_no'] && $mwwWl == ''){
                $mwwWl = $v2['merchant_express_no'];
                $mwwWlName = $v2['merchant_express'];
            }
            if($v2['merchant_express_no'] && $mwwWl){
                if($mwwWl != $v2['merchant_express_no']) $mwwWlFlag = 2;
            }
            //----
            if($v2['type'] == 2 || $v2['tui_user_get'] == 2 || !$v2['merchant_express_no']) $send2 = 2;
        }
        //
        if($mwwWl == '') $mwwWlFlag = 2;
        $wldata = [];
        if($mwwWlFlag == 1){
            $wldata = orderWuLiu($mwwWl);
            if($wldata['status'] == 200){
                $wldata['time'] = $wldata['msg'][0]['time'];
                $wldata['msg'] = $wldata['msg'][0]['context'];
            }
        }
        return json(['status'=>200,'msg'=>$detailsold[0],'goods'=>$detailsold
            ,'wldata' => $wldata,'mwwWlFlag' => $mwwWlFlag,'mwwWl' => $mwwWl,'mwwWlName' => $mwwWlName,'send2' => $send2,'is_sale' => $order['is_sale']
        ]);
    }
    public function getWlDataForSale()
    {
        extract(input());
        $order_contract = Db::table('up_self_order')->where('order_id',$order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        if($order_contract != 1){
            $good_table = 'up_goods';
        }
        $where = [
            't.order_id' => $order_id,
            't.order_erp_wl_no' => $order_erp_wl_no
        ];
        $resOld = Db::table('up_self_order_tui t')
            ->where($where)
            ->group('merchant_express_no')
            ->field('merchant_express,merchant_express_no')
            ->select();
        $res = [];
        foreach ($resOld as $k => $v){
            if($v['merchant_express_no']) $res[] = $v;
        }
        foreach ($res as $k => $v){
            $int = $k + 1;
            $res[$k]['name'] = '包裹' . $int;
            $image = Db::table('up_self_order_tui')->alias('t')
                ->join("up_self_order_detail od",'t.order_detail_id=od.detail_id','LEFT')
                ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                ->where($where)
                ->where('merchant_express_no',$v['merchant_express_no'])
                ->field('good_thumb,od.num')
                ->select();
            $res[$k]['image'] = $image;
            $res[$k]['nums'] = array_sum(array_column($image,'num'));
            //
            $res[$k]['time'] = '';
            $res[$k]['msg'] = '';
            $wldata = orderWuLiu($v['merchant_express_no']);
            if($wldata['status'] == 200){
                $res[$k]['time'] = $wldata['msg'][0]['time'];
                $res[$k]['msg'] = $wldata['msg'][0]['context'];
            }
        }
        return json(['status'=>200,'msg'=>$res]);
    }
    public function errorForAddress()
    {
        extract(input());
        if(!$express || !$express_no) return json(['status' => 0, 'msg' => '请填写物流信息']);
        Db::table('up_self_order_tui')
            ->where('order_id',$order_id)
            ->where('status',1)
            ->where('express_no','')
            ->update([
                'express' => $express,
                'express_no' => $express_no
            ]);
        Db::table('up_self_order')->where('order_id',$order_id)
            ->update([
                'panson_error' => 2
            ]);
        return json(['status'=>200,'msg'=>'提交成功']);
    }
    public function getSizes()
    {
        $user_id = $_POST['user_id'];
        $good_id = $_POST['good_id'];
        $can = $this->getSonByUser($user_id);
        if($can['status'] != 200){
            return json($can);
        }
        $sondata = $can['msg'];
        //TODO：nowyear：立即购买时，传进去时的；换货时，选择order里面的年
        if(isset($_POST['nowyear']) && $_POST['nowyear']){
            $sondata['uson_year'] = $_POST['nowyear'];
        }
        $sizes = $this->getInSizeForGood($good_id,'',$sondata);
        return json(['status'=>200,'msg'=>$sizes]);
    }
    /**
     * 获取自营商品的规格信息
     */
    public function getZiyingSizes()
    {
        extract(input());
        $good = Db::table('up_self_goods')
            ->where('good_id',$good_id)
            ->find();
        if($good['good_status'] != 1){ //非上架不展示
            return json(['status'=>0,'msg'=>'此商品已下架']);
        }
        //规格和对应价格
        $guige = json_decode($good['good_guige'],true);
        $guige_price = Db::table('up_self_goods_attr')
            ->where('goods_id',$good_id)
            ->where('is_delete',0)
            ->select();
        return json(['status'=>200,'msg'=>$good,'guige'=>$guige,'guige_price'=>$guige_price]);
    }
    public function getWlData()
    {
        extract(input());
        $order_contract = Db::table('up_self_order')->where('order_id',$order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        if($order_contract != 1){
            $good_table = 'up_goods';
        }
        $resOld = Db::table('up_self_order_detail')
            ->where('order_id',$order_id)
            ->group('detail_express_no')
            ->field('detail_express,detail_express_no')
            ->select();
        $res = [];
        foreach ($resOld as $k => $v){
            if($v['detail_express_no']) $res[] = $v;
        }
        foreach ($res as $k => $v){
            $int = $k + 1;
            $res[$k]['name'] = '包裹' . $int;
            $image = Db::table('up_self_order_detail')->alias('od')
                ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
                ->where('order_id',$order_id)
                ->where('detail_express_no',$v['detail_express_no'])
                ->field('good_thumb,od.num')
                ->select();
            $res[$k]['image'] = $image;
            $res[$k]['nums'] = array_sum(array_column($image,'num'));
            //
            $res[$k]['time'] = '';
            $res[$k]['msg'] = '';
            $wldata = orderWuLiu($v['detail_express_no']);
            if($wldata['status'] == 200){
                $res[$k]['time'] = $wldata['msg'][0]['time'];
                $res[$k]['msg'] = $wldata['msg'][0]['context'];
            }
        }
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * msg：订单快递公司和单号、缩略图
     * wldata：
     *      status为200时展示快递信息，其他值时不展示，只展示里面的msg即可
     *      msg为物流信息数组
     *      wlstate为快递单当前状态，0在途，1揽收，2疑难，3签收，4退签，5派件，6退回
     */
    public function getWlInfo()
    {
        extract(input());
        $order_id = Db::table('up_self_order_detail')->where('detail_id',$detail_id)->value('order_id');
        $order_contract = Db::table('up_self_order')->where('order_id',$order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        if($order_contract != 1){
            $good_table = 'up_goods';
        }
        $data = Db::table('up_self_order_detail')->alias('od')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where('detail_id',$detail_id)
            ->field('detail_express,detail_express_no,good_thumb')
            ->find();
        $wldata = orderWuLiu($data['detail_express_no']);
        if($wldata['status'] != 200){
            $wldata['status'] = 200;
            $wldata['msg'] = [];
        }
        return json(['status'=>200,'msg'=>$data,'wldata'=>$wldata]);
    }
    /**
     * 修改尺码
     */
    public function changeSize()
    {
        extract(input());
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        if($order['order_contract'] != 2) {
            return json(['status'=>0,'msg'=>'只有增补订单才可以修改尺码']);
        }
        $time = time();
        $hours = Db::table('up_about')->where('id',9)->value('content');
//        $hours = (int)$hours;
        $pay_time_24 = strtotime($order['pay_time']) + 3600*$hours;
        if($order['is_pay'] == 1 && $order['is_send'] == 0 && $order['order_cancel_status'] <= 2 && $pay_time_24 >= $time){
            $changes = json_decode($changes,true);
            Db::startTrans();
            try{
                $sondata = Db::table('up_u_user_son')->where('uson_id',$order['order_user_son_id'])
                    ->field('uson_id,uson_username,user_gender,uson_year,uson_school,uson_idcard,uson_size')
                    ->find();
                foreach ($changes as $k=>$v){
                    $old = Db::table('up_self_order_detail')
                        ->where('detail_id',$v['detail_id'])
                        ->field('attr_id,goods_id,num,pay_year')
                        ->find();
                    if($v['attr_id'] != $old['attr_id']){
                        $o_g = Db::table('up_goods')
                            ->where('good_id',$old['goods_id'])
                            ->field("good_name,good_color,good_coding_less")
                            ->find();
                        //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                        $less_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $v['attr_id'])
                            ->where('spec_size_q', 2)
                            ->value('spec_good_coding_less');
                        if ($less_code) { //说明此款号有Q款，再去判断
                            $erp = 2;
                        } else {
                            $erp = 1;//压根没有Q款
                        }
                        $sure = $this->getStudentGoods($sondata['uson_school'], $old['pay_year'], $sondata['user_gender'], $erp, $o_g['good_coding_less']);
                        $size_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $v['attr_id'])
                            ->where('spec_size_q', $sure['sg_good_q'])
                            ->value('spec_size_two');
                        if(empty($size_code)){
                            Db::rollback();
                            return json(['status'=>0,'msg'=>'尺码有误，请刷新重试，或重新选择尺码~']);
                        }
                        $unique_code = $sure['sg_good_coding'] . $size_code;
                        if ($sure['sg_sign']) {
                            $unique_code .= $sure['sg_sign'];
                        }
                        //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                        Db::table('up_self_order_detail')->where('detail_id',$v['detail_id'])->update([
                            'goods_coding_unique' => $unique_code,
                            'attr_id' => $v['attr_id'],
                            'goods_info' => $o_g['good_color'] . '/' . $v['attr_id']
                        ]);
                    }
                }
                Db::commit();
                return json(['status'=>200,'msg'=>'修改成功！']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['status'=>0,'msg'=>'修改失败！']);
            }
        }else{
            return json(['status'=>0,'msg'=>'已发货或已超过调换时间范围，不可修改！']);
        }

    }
    /**
     * 手动取消订单
     *
     */
    public function cancleOrder()
    {
        extract(input());
        $is_pay = Db::table('up_self_order')->where('order_id', $order_id)->value('is_pay');
        if($is_pay != 0){
            return json(['status'=>0,'msg'=>'只有未支付订单才可以取消']);
        }
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        Db::startTrans();
        try{
            $field = 'goods_id,num,attr_id';
            $details = Db::table('up_self_order_detail')
                ->where('order_id',$order_id)
                ->field($field)
                ->select();
            foreach ($details as $k=>$v){
                if($contract == 1){
                    //1、加上商品的库存
                    Db::table('up_self_goods')->where('good_id',$v['goods_id'])->setInc('good_stock',$v['num']);
                    //2、加上attr的库存
                    Db::table('up_self_goods_attr')->where('attr_id',$v['attr_id'])->setInc('stock',$v['num']);
                }
            }
            //3、改变订单状态
            Db::table('up_self_order')->where('order_id',$order_id)->setField('is_pay',2);
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 支付完取消订单
     *
     */
    public function canclePayOrder()
    {
        extract(input());
//        $order_id=79;
        $order = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('order_no,order_id,total_price,pay_type,user_id,is_pay,order_contract,is_send,order_cancel_status,order_push_erp,pay_time')->find();
//         && $order['order_push_erp'] == 1
        if($order['is_pay'] == 1 && $order['order_contract'] <= 2 && $order['is_send'] == 0 && $order['order_cancel_status'] <= 2){
            $today = date('Y-m-d');
//            if($order['order_contract'] == 1){
//                $paydate = date('Y-m-d',strtotime($order['pay_time']));
//                $today = date('Y-m-d');
//                if($paydate < $today) return json(['status'=>0,'msg'=>'已超出取消订单允许时间范围']);
//            }
            if($order['pay_time'] <= '2022-11-08 23:59:59') return json(['status'=>0,'msg'=>'此单已超出退款时间范围']);
            if(!isset($cancel_remark) || $cancel_remark == ''){
                $cancel_remark = '';
            }
            if(isset($exchange_name) && $exchange_name){
                $cancel_remark = $exchange_name . '。' . $cancel_remark;
            }
            //如果可以退，别忘了order_cancel_push_erp改为2，退货就不推了
            $autoFlag = Db::table('up_about')->where('id',18)->value('content');
            $cantui = false;
            if($autoFlag == 1){
                if($order['order_push_erp'] == 1){
                    $cantui = true;
                }else{
                    if($order['order_contract'] == 1){ // 自营
                        $master = [
                            'order_sn' => '',
                            'deal_code' => $order['order_no'],
                            'ly_type' => 'openshop'
                        ];
                        $result = $this->curl_oms('order.cancel.delivery', json_encode($master));
                        if (isset($result['status']) && $result['status'] == 'api-success') {
                            $master = [
                                'order_sn' => '',
                                'deal_code' => $order['order_no']
                            ];
                            $this->curl_oms('order.zwx', json_encode($master));
                            $master = [
                                'order_sn' => $order['order_no']
                            ];
                            $result = $this->curl_oms('order.detail.get', json_encode($master));
                            if(isset($result['data']['order_status']) && $result['data']['order_status'] == 3){
                                $cantui = true;
                            }else{
                                if(isset($result['data']['shipping_status']) && $result['data']['shipping_status'] == 7) return json(['status'=>0,'msg'=>'订单已进入发货流程! 无法取消']);
                                return json(['status'=>0,'msg'=>'取消失败，请联系客服']);
                            }
                        }else{
                            $master = [
                                'order_sn' => $order['order_no']
                            ];
                            $result = $this->curl_oms('order.detail.get', json_encode($master));
                            if(isset($result['data']['shipping_status']) && $result['data']['shipping_status'] == 7) return json(['status'=>0,'msg'=>'订单已进入发货流程! 无法取消']);
                            return json(['status'=>0,'msg'=>'取消失败，请联系客服']);
                        }
                    }else{ // 增补
                        $cantui = false;
                    }

                }
            }
            if($cantui == true){
                $update  = [
                    'order_cancel_status'=>3,
                    'order_cancel_pay'=>3,
                    'order_master_status'=>4,
                    'is_pay'=>2,
                    'order_cancel_money'=>$order['total_price'],
                    'auto_cancel'=>1,
                    'order_cancel_number' => 'T' . time() . rand(1000000,9999999),
                    'order_cancel_time'=> date('Y-m-d H:i:s'),
                    'updated_at'=> date('Y-m-d H:i:s',time()),
                ];
                if($order['order_push_erp'] != 1) $update['order_cancel_push_erp'] = 2;
                $payInfo = [
                    'total_price' => $order['total_price'],
                    'money' => $order['total_price'],
                    'number' => $order['order_no']
                ];
                $refundNo = $update['order_cancel_number'];
                if($order['pay_type'] == 1){ //微信
                    $tuiwx = new \app\api\controller\Tuiwx();
                    $res = $tuiwx->refundWx($payInfo,$refundNo);
                }elseif ($order['pay_type'] == 2){ //支付宝
                    $tuiali = new \app\api\controller\Ali();
                    $res = $tuiali->refund($payInfo,$refundNo);
                }else{
                    return json(['status'=>0,'msg'=>'订单有误']);
                }
                if($res['status'] != 200) return json(['status'=>0,'msg'=>$res['msg']]);
            }else{
                $update = [
                    'order_cancel_status' => 4,
                    'auto_cancel' => 1,
                    'order_cancel_remark' => $cancel_remark,
                    'order_cancel_time' => date('Y-m-d H:i:s')
                ];
                if($order['order_contract'] == 2 && $autoFlag == 1) $update['auto_cancel'] = 2;
            }
            $res = Db::table('up_self_order')->where('order_id',$order_id)
                ->update($update);
            if($res){
                if($cantui == true) {
                    allInRevenue(2,$order['total_price'],$order['user_id'],4,$order_id,0,$order_id);
                    return json(['status'=>200,'msg'=>'取消成功']);
                }
                return json(['status'=>200,'msg'=>'提交成功，取消中']);
            }else{
                return json(['status'=>0,'msg'=>'取消失败，请刷新重试']);
            }
        }else{
            return json(['status'=>0,'msg'=>'订单已进入发货流程！无法取消']);
        }
    }
    /**
     * 确认收货
     */
    public function receiptMyOrder()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->value('is_send');
        if($is_send != 1){
            return json(['status'=>0,'msg'=>'只有待收货订单才可以确认收货']);
        }
        $update = [
            'is_send' => 2,
            'confirm_time' => $today
        ];
        $res = Db::table('up_self_order')->where('order_id', $order_id)->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 换货的确认收货
     */
    public function receiptSaleOrder()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $where = [
            't.order_id' => $order_id,
            't.order_erp_wl_no' => $order_erp_wl_no
        ];
        $update = [
            'tui_user_get' => 2,
            'updated_at' => $today
        ];
        $res = Db::table('up_self_order_tui t')
            ->where($where)
            ->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 增补售后的回寄
     */
    public function userSaleExpress()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $where = [
            't.order_id' => $order_id,
            't.order_erp_wl_no' => $order_erp_wl_no
        ];
        $update = [
            'express' => $express,
            'express_no' => $express_no
        ];
        $res = Db::table('up_self_order_tui t')
            ->where($where)
            ->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 删除订单：只有已取消的才可以删除订单
     */
    public function delMyOrder()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $is_pay = Db::table('up_self_order')->where('order_id', $order_id)->value('is_pay');
        if($is_pay != 2){
            return json(['status'=>0,'msg'=>'只有已取消的订单才可以删除']);
        }
        $update = [
            'is_delete' => 1,
            'deleted_at' => $today
        ];
        $res = Db::table('up_self_order')->where('order_id', $order_id)->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 评价我的订单：特殊符号作为分隔符’__‘
     */
    public function orderComment()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->value('is_send');
        if($is_send != 2){
            return json(['status'=>0,'msg'=>'只有待评价订单才可以评价']);
        }
        $comments = json_decode($comments,true);
        //
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        $goods_comment_table = 'up_self_goods_comment';
        if($contract != 1){
            $good_table = 'up_goods';
            $goods_comment_table = 'up_goods_comment';
        }
        //
        Db::startTrans();
        try{
            foreach ($comments as $k=>$vv){
                $det = Db::table('up_self_order_detail')->where('detail_id', $vv['detail_ids'])->field('goods_id,goods_info')->find();
                $v = $det['goods_id'];
                //1、重新算好评率
                $good = Db::table($good_table)->where('good_id',$v)->field('good_score,good_comment')->find();
                $allscore = ($good['good_score'] * $good['good_comment']) + ($vv['scores'] * 20);
                $nowscore = round($allscore/($good['good_comment']+1),1);
                Db::table($good_table)->where('good_id',$v)->setField('good_score',$nowscore);
                //2、评论数加1
                Db::table($good_table)->where('good_id',$v)->setInc('good_comment',1);
                //3、入评论表
                $comment = [
                    'comment_order_id' => $order_id,
                    'comment_type' => $contract,
                    'comment_good_id' => $v,
                    'comment_detail_id' => $vv['detail_ids'],
                    'comment_content' => $vv['contents'],
                    'comment_image' => trim($vv['pics'],','),
                    'comment_guige' => $det['goods_info'],
                    'comment_star' => $vv['scores'],
                    'comment_user_id' => $user_id,
                    'comment_time' => $today
                ];
                Db::table($goods_comment_table)->insert($comment);
            }
            //4、改变订单状态(已评论)
            Db::table('up_self_order')->where('order_id',$order_id)->setField('is_send',3);
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }

    /**
     * 查看评价
     * @return \think\response\Json
     */
    public function seeOrderComment()
    {
        extract(input());
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->value('is_send');
        if($is_send != 3){
            return json(['status'=>0,'msg'=>'只有已评价订单才可以查看']);
        }
        //
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        $goods_comment_table = 'up_self_goods_comment';
        if($contract != 1){
            $good_table = 'up_goods';
            $goods_comment_table = 'up_goods_comment';
        }
        //
        $field = 'num,unit_price,goods_info,good_name,good_thumb';
        $field .= ',comment_content,comment_image,comment_star';
        $comments = Db::table($goods_comment_table)->alias('c')
            ->join("$good_table g",'c.comment_good_id=g.good_id','LEFT')
            ->join('up_self_order_detail od','c.comment_detail_id=od.detail_id','LEFT')
            ->where('comment_order_id',$order_id)
            ->where('comment_type',$contract)
            ->field($field)
            ->select();
        foreach ($comments as $k=>$v){
            if($v['comment_image']){
                $comments[$k]['comment_image'] = explode(',',$v['comment_image']);
            }
        }
        return json(['status'=>200,'msg'=>$comments]);
    }
    /**
     * 退货原因
     */
    public function tuiReason()
    {
        extract(input());
        if(!isset($type) || !$type) $type = 1;
        $res = Db::table('up_return')
            ->where('exchange_type',$type)
            ->select();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 申请售后：只有已发货后的才可以
     * 后台说明：TODO：
     *          1、如果订单1件商品：同意或拒绝则tui_status已完成
     *          2、如为多件，sale_status为1时同意或拒绝则tui_status已完成
     * $detail_ids='445';$order_id=464;$type=1;$newsizes='150';$user_id=1;$remark='换货';$express='顺丰';$express_no='SF666666666';
     */
    public function afterSaleOrder()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $orderFor3 = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('is_send,is_pay,pay_time,order_cancel_status,order_school,order_erp_sex')->find();
		$is_send = $orderFor3['is_send'];
        if ($is_send < 1 || $orderFor3['is_pay'] != 1 || $orderFor3['order_cancel_status'] > 2) {
            return json(['status' => 0, 'msg' => '只有未取消的已发货订单才可以申请售后']);
        }
        if($orderFor3['pay_time'] <= '2022-11-08 23:59:59') return json(['status'=>0,'msg'=>'此单已超出售后时间范围']);
        $detail_ids = explode(',', trim($detail_ids, ','));
        //
        $oson = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('order_contract,order_user_son_id,order_erp_year')->find();
        $contract = $oson['order_contract'];
        if($contract == 3) return json(['status' => 0, 'msg' => '订单入口错误，请从‘我的’进入订单售后']);
        if(isset($exchange_name) && $exchange_name){
            $remark = $exchange_name . '。' . $remark;
        }
        $good_table = 'up_self_goods';
        $goods_comment_table = 'up_self_goods_comment';
        $tui_user_son_id = 0;
        if($contract != 1){
            $good_table = 'up_goods';
            $goods_comment_table = 'up_goods_comment';
            $sondata = Db::table('up_u_user_son')->where('uson_id',$oson['order_user_son_id'])
                ->field('uson_id,uson_username,user_gender,uson_year,uson_school,uson_idcard,uson_size')
                ->find();
            if(empty($sondata)){
                return json(['status' => 0, 'msg' => '学生信息有误，请重新选择学生']);
            }
            $tui_user_son_id = $sondata['uson_id'];
            if($orderFor3['order_school']){
                $oldrealSch = Db::table('up_school')->where('school_erp',$orderFor3['order_school'])->value('school_id');
                if($oldrealSch) $sondata['uson_school'] = $oldrealSch;
            }
            if($orderFor3['order_erp_sex']) $sondata['user_gender'] = $orderFor3['order_erp_sex'];
        }
        if($express || $express_no || !isset($pic_list)) return json(['status' => 0, 'msg' => '请更新版本，杀死应用重新进入即可']);
        //
        $haveTui = Db::table('up_self_order_tui')
            ->where('order_detail_id', 'in',$detail_ids)
            ->where('status', 1)
            ->field('tui_id')
            ->find();
        if($haveTui) return json(['status' => 0, 'msg' => '请勿重复申请']);
        Db::startTrans();
        try {
            if($type == 1) { //如果没有选择尺码的界面，说明版本不对，要更新版本
                $newsizes = explode(',', trim($newsizes, ','));
                if (count($newsizes) != count($detail_ids)) {
                    return json(['status' => 0, 'msg' => '请选择要换货的尺寸,每个都要选哦']);
                }
            }
//            $tuihave = Db::table('up_self_order_tui')->where('order_detail_id', 'in',$detail_ids)->find();
//            if($tuihave){
//                Db::table('up_self_order_tui')->where('order_detail_id', 'in',$detail_ids)->update([
//                    'is_delete' => 1,
//                    'deleted_at' => $today
//                ]);
//            }
            $erp_wl_no = 'app' . time() . rand(10, 99) . $user_id;
            $tuiAll = [];
            if($pic_list){
                $pic_list = explode(',',$pic_list);
                foreach ($pic_list as $k => $v){
                    $varr = explode('.',$v);
                    unset($varr[count($varr) - 1]);
                    $pic_list[$k] = implode('.',$varr) . '.jpg';
                }
                $pic_list = implode(',',$pic_list);
            }
            foreach ($detail_ids as $k => $v) {
                //1、入售后表：
                $number = time() . rand(100000, 999999) . $k;
                $tui = [
                    'user_id' => $user_id,
                    'tui_type' => $contract,
                    'tui_user_son_id' => $tui_user_son_id,
                    'order_id' => $order_id,
                    'order_detail_id' => $v,
                    'order_no' => $number,
                    'order_erp_wl_no' => $erp_wl_no,
                    'type' => $type,//1换货 2退款
                    'refund_price' => 0,
                    'remark' => $remark,
                    'pic_list' => $pic_list,
                    'express' => $express,
                    'express_no' => $express_no,
                    'created_at' => $today
                ];
                $suan = Db::table('up_self_order_detail')->where('detail_id', $v)->field('th_status,num,unit_price,detail_express_no')->find();
                if(!$suan['detail_express_no']){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '选择有误，不应包含未发货的衣服']);
                }
//                if($contract == 2 && $suan['th_status'] != 0){ //只有自营才可以拒绝的再申请
//                    Db::rollback();
//                    return json(['status' => 0, 'msg' => '已经有重复的售后数据了，请重新选择']);
//                }
                $tui['refund_num'] = $suan['num'];
                if($type == 1){ //换货的话记录下原尺码
                    $oldSD = $this->getLastInfo($v);
                    $tui['erp_old_size'] = $oldSD['erp_new_size'];
                }
                if($type == 2){ //如果是退款的话退多少
                    $refund_price = $suan['num'] * $suan['unit_price'];
                    $tui['refund_num'] = $suan['num'];
                    $tui['refund_price'] = $refund_price;
                    $tui['should_money'] = $refund_price;
                }
                //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                if($contract == 2 && $type == 1) {
                    $old = Db::table('up_self_order_detail')
                        ->where('detail_id', $v)
                        ->field('attr_id,goods_id,num,goods_coding_unique,pay_year')
                        ->find();
                    $tui['erp_new_size'] = $old['attr_id'];
                    $tui['erp_huan_uninumber'] = $old['goods_coding_unique'];
                    $newsizes[$k] = (int)$newsizes[$k];
                    if(empty($newsizes[$k]) || $newsizes[$k] <= 0){
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '请选择要调换的尺码']);
                    }
                    if ($newsizes[$k] != $old['attr_id']) {
                        $o_g = Db::table('up_goods')
                            ->where('good_id', $old['goods_id'])
                            ->field("good_name,good_color,good_coding_less")
                            ->find();
                        $less_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $newsizes[$k])
                            ->where('spec_size_q', 2)
                            ->value('spec_good_coding_less');
                        if ($less_code) { //说明此款号有Q款，再去判断
                            $erp = 2;
                        } else {
                            $erp = 1;//压根没有Q款
                        }
                        $sure = $this->getStudentGoods($sondata['uson_school'], $old['pay_year'], $sondata['user_gender'], $erp, $o_g['good_coding_less']);
                        $size_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $o_g['good_coding_less'])
                            ->where('spec_size', $newsizes[$k])
                            ->where('spec_size_q', $sure['sg_good_q'])
                            ->where('spec_size_type', 1)
                            ->value('spec_size_two');
                        if(empty($size_code)){
                            Db::rollback();
//                            return json(['status'=>0,'msg'=>$sondata['uson_school'].'>'.$old['pay_year'].'>'.$sondata['user_gender'].'>'.$erp.'>'. $o_g['good_coding_less'] . '尺码有误，请刷新重试，或重新选择尺码~']);
                            return json(['status'=>0,'msg'=>'尺码有误，请刷新重试，或重新选择尺码~~']);
                        }
                        $unique_code = $sure['sg_good_coding'] . $size_code;
                        if ($sure['sg_sign']) {
                            $unique_code .= $sure['sg_sign'];
                        }
                        $tui['erp_new_size'] = $newsizes[$k];
                        $tui['erp_huan_uninumber'] = $unique_code;
                    }
                    //年份和交期
                    $days = Db::table('up_school')->where('school_id',$sondata['uson_school'])->value('school_done');
                    if($days && (int)$days > 0 ){
                        $days = (int)$days;
                    }else{
                        $days = Db::table('up_about')->where('id',10)->value('content');
                        $days = (int)$days;
                    }
                    $time = time();
                    $days_after = date("Ymd",($time + 3600*$days*24));
                    $tui['erp_year'] = $oson['order_erp_year'];
                    $tui['erp_done'] = $days_after;
                }
                if($contract == 1 && $type == 1) {
                    $old = Db::table('up_self_order_detail')
                        ->where('detail_id', $v)
                        ->field('attr_id,goods_id,num,goods_coding_unique,pay_year')
                        ->find();

                    $newsizes[$k] = (int)$newsizes[$k];
                    if(empty($newsizes[$k]) || $newsizes[$k] <= 0){
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '请选择要调换的尺码']);
                    }
                    $ziyingCode = Db::table('up_self_goods')->where('good_id', $old['goods_id'])->value("good_coding");
                    $ziyingInfo = Db::table('up_self_goods_attr')->where('attr_id',$newsizes[$k])->value('sign_str');
                    if(!$ziyingCode || !$ziyingInfo){
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '数据有误，请刷新重试~']);
                    }
                    $two = $this->getZiyingSizeTwo($ziyingInfo);
                    if($two) {
                        $ziyingCode .= $two;
                    }else{
                        $ziyingCode .= $ziyingCode;
                    }
                    $tui['erp_new_size'] = $ziyingInfo; //这个其实是尺码信息，不是规格id了
                    $tui['erp_huan_uninumber'] = $ziyingCode; //衣服尺码
                }
                //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//                dump($tui);die;
                $tuiAll[] = $tui;
            }
            $haveTui = Db::table('up_self_order_tui')
                ->where('order_detail_id', 'in',$detail_ids)
                ->where('status', 1)
                ->field('tui_id')
                ->find();
            if($haveTui){
                Db::rollback();
                return json(['status' => 0, 'msg' => '请勿重复申请']);
            }
            Db::table('up_self_order_tui')->insertAll($tuiAll);
            //2、改详情表
            Db::table('up_self_order_detail')->where('detail_id', 'in',$detail_ids)->update([
                'refund_status' => 1,
                'th_status' => $type,
                'deleted_at' => $today
            ]);
            //3、改order表售后状态
            $goodsnum = Db::table('up_self_order_detail')->where('order_id', $order_id)->count();
            if($goodsnum > 1){ //超出一件：全售后则order为售后中，否则不改
                $goods_errornum = Db::table('up_self_order_detail')
                    ->where('order_id', $order_id)
                    ->where('th_status', '>',0)
                    ->count();
                if($goodsnum == $goods_errornum){
                    Db::table('up_self_order')->where('order_id', $order_id)->update([
                        'sale_status' => 1,
                        'tui_status' => 0,
                    ]);
                }
            }else{ //只一件：detail售后状态order售后状态
                Db::table('up_self_order')->where('order_id', $order_id)->update([
                    'sale_status' => $type+1,
                    'tui_status' => 0,
                ]);
            }
            Db::commit();
            $title = '退换货通知';
            $content = '发起退换货后，我们将在收货后进行核实，并为您处理退换货事宜。';
            allInNotice($title,$content,3,$user_id,$order_id,$contract);
            try{
                $this->Jpush(1, $user_id, '发起售后通知', ['n_id' => $order_id,'type' => $contract,'n_type' => 3]);
            }catch(\Exception $e){

            }
            return json(['status' => 200, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败，请刷新重试']);
        }
    }
    /**
     * 用户售后回寄
     * @return \think\response\Json
     */
    public function userHuanExpress()
    {
        extract(input());
        if(!$express || !$express_no){
            return json(['status' => 0, 'msg' => '快递公司和快递单号不能为空！']);
        }
        $where = [
            't.order_id' => $order_id,
            't.order_erp_wl_no' => $order_erp_wl_no
        ];
        $update = [
            'express' => $express,
            'express_no' => $express_no
        ];
        $res = Db::table('up_self_order_tui t')
            ->where($where)
            ->update($update);
        if($res){
            try{
                //2、售后的推不管退还是换，先推个售后
                $where2 = [];
                $where2['tui_type'] = 1;
                $where2['status'] = 2;
                $where2['erp_push'] = 1;

                $field = 'o.order_no,o.order_id,all_goods_price,total_price,express_original_price,o.name,o.mobile,o.address,o.order_address2,o.order_back_order_id';
                $field .= ',t.type,t.order_erp_wl_no,o.pay_type';
                $field .= ',t.express,t.express_no,t.remark,t.created_at,t.status_time';
                $v = Db::table('up_self_order_tui')->alias('t')
                    ->join('up_self_order o', 't.order_id=o.order_id', 'LEFT')
                    ->where($where2)
                    ->where('order_erp_wl_no',$order_erp_wl_no) //必须是app的推给过oms的单;
                    ->where('new_erp_have',2) //必须是app的推给过oms的单;
                    ->field($field)
                    ->find();
                if ($v){
                    $master = [];
                    $master['sell_return_record'] = [
                        'order_sn' => $v['order_no'],
                        'refund_code' => $v['order_erp_wl_no'] . 'tapp',
                        'return_ck_code' => '', // 退货仓库代码
                        'return_kw_code' => '', // 退货库位代码
                        'return_shipping_sn' => $express_no,
                        'shipping_name' => $express,
                        'shipping_sn' => $express_no,
                        'return_type' => 1
                    ];
                    $field = 'od.detail_id sku,num goods_number,unit_price shop_price';
                    $details = Db::table('up_self_order_tui')->alias('t')
                        ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                        ->where($where2)
                        ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                        ->field($field)
                        ->select();
                    foreach ($details as $k222 => $v222){
                        $oldSD = $this->getLastInfo($v222['sku'],$v['type']);
                        $details[$k222]['sku'] = $oldSD['erp_huan_uninumber'];
                    }
                    if(isset($oldSD['order_erp_wl_no']) && $oldSD['order_erp_wl_no']){
                        $master['sell_return_record']['order_sn'] = $oldSD['order_erp_wl_no']; // 确保单号正确
                    }
                    $master['sell_return_record']['order_return_goods'] = $details;
                    $result = $this->curl_oms('order.return.add', json_encode($master));
                    Db::table('up_zzzz_oms')->insert([
                        'nono' => 'oid=>' . $order_id,
                        'content' => json_encode($result),
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    if (isset($result['status']) && $result['status'] == 'api-success') {
                        Db::table('up_self_order_tui')
                            ->where($where2)
                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                            ->setField('erp_push', 2);
                    }
                }
            }catch(\Exception $e){}
            return json(['status' => 200, 'msg' => '操作成功，请您耐心等待~']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败，请刷新重试']);
        }
    }
    /**
     * 查看退货商品的详情
     * @return \think\response\Json
     */
    public function getTuiInfo()
    {
        extract(input());
        //
        $order_id = Db::table('up_self_order_detail')->where('detail_id', $detail_id)->value('order_id');
        $contract = Db::table('up_self_order')->where('order_id', $order_id)->value('order_contract');
        $good_table = 'up_self_goods';
        if($contract != 1){
            $good_table = 'up_goods';
        }
        //typeorder_no
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status';
        $field .= ',remark,merchant_remark,t.created_at,order_erp_wl_no order_no,status,express,express_no,merchant_express,merchant_express_no';
        $field .= ',tui_user_get,erp_new_size';
        $data = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order_detail od','t.order_detail_id=od.detail_id','LEFT')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where('order_detail_id', $detail_id)
            ->where('t.is_delete', 0)
            ->order('created_at desc')
            ->field($field)
            ->find();
        return json(['status' => 200, 'msg' =>$data]);
    }
    /**
     * 开发票
     * @return \think\response\Json
     */
    public function fapiaoOrder()
    {
        extract(input());
//        $user_id=393018;$order_id=88;$fapiao_type=1;$fapiao_head='hhhhhhhhhhhhhhh';$fapiao_email='644799250@qq.com';$fapiao_remark='beizhu';
        error_reporting(0);
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('is_send,fapiao_status,fapiao_head,order_contract,order_user_son_id,sale_status,order_school,order_no,express_original_price')->find();
        if ($is_send['is_send'] < 2) {
            return json(['status' => 0, 'msg' => '只有已收货订单才可以开具发票']);
        }
        if ($is_send['fapiao_status'] != 0) {
            if(empty($is_send['fapiao_head'])){
                return json(['status' => 0, 'msg' => '您已经开过发票了']);
            }else{
                return json(['status' => 0, 'msg' => '此单不具备开发票条件']);
            }
        }
        //
        $shouhou_habe = Db::table('up_self_order_detail')
            ->where('order_id', $order_id)
            ->where('th_status', '<>',0)
            ->where('refund_status', '<>',2)
            ->find();
        if ($shouhou_habe) {
            return json(['status' => 0, 'msg' => '此订单有进行中的售后，暂不能开票']);
        }
        $detailids = Db::table('up_self_order_detail')->where('order_id', $order_id)->column('detail_id');
        $detailids_no = Db::table('up_self_order_tui')
            ->where('order_detail_id', 'in',$detailids)
            ->where('type', 2)
            ->where('status', 'in','1,2')
            ->column('order_detail_id');
        $where = [
            'order_id' => $order_id
        ];
        if($detailids_no){
            $where['detail_id'] = ['not in',$detailids_no];
        }
        $details = Db::table('up_self_order_detail')
            ->where($where)
            ->field('detail_id,num,unit_price')
            ->select();
        if(empty($details)){
            return json(['status' => 0, 'msg' => '此订单已经售后，不能开票']);
        }
        $mingxiPrice = 0;
        foreach ($details as $k=>$v){
            $mingxiPrice += ($v['unit_price']*$v['num']);
        }
        if($is_send['express_original_price'] > 0){
            $mingxiPrice += $is_send['express_original_price'];
//            $mingxi[] = [
//                'goodsName' => '*运输服务*运费',
//                'num' => 1,
//                'price' => $is_send['express_original_price'],
//                'unit' => '-',
//                'withTaxFlag' => '1',
//                'taxRate' => '0.13'
//            ];
        }
        $mingxi = [
            'goodsName' => '学生校服',
            'withTaxFlag' => '1',
            'num' => 1,
            'price' => $mingxiPrice,
            'unit' => '套',
            'taxRate' => '0.13'
        ];
        //
        if($is_send['order_contract'] != 1){
            $sch = Db::table('up_school')->where('school_erp',$is_send['order_school'])
                ->field('school_head,school_shui')->find();
            if(empty($sch)){
                return json(['status' => 0, 'msg' => '学校信息有误，无法开票']);
            }
            if(empty($sch['school_head']) || empty($sch['school_shui'])){
                return json(['status' => 0, 'msg' => '学校信息不全，请稍后再开票']);
            }
            $fapiao = [
                'fapiao_status' => 1,
                'fapiao_type' => 2,
                'fapiao_head' => $sch['school_head'],
                'fapiao_shui' => $sch['school_shui'],
                'fapiao_email' => $fapiao_email,
                'fapiao_remark' => $fapiao_remark,
                'fapiao_time' => $today
            ];
        }else{
            $fapiao = [
                'fapiao_status' => 1,
                'fapiao_type' => $fapiao_type,
                'fapiao_head' => $fapiao_head,
                'fapiao_shui' => '',
                'fapiao_email' => $fapiao_email,
                'fapiao_remark' => $fapiao_remark,
                'fapiao_time' => $today
            ];
            if($fapiao_type == 2 ){
                $fapiao['fapiao_shui'] = $fapiao_shui;
            }
        }
        //如果要开启自动化，把这一块注释掉就行了-start---
        $fapiao['fapiao_status'] = 2;
        $fapiao['fapiao_ordernum'] = '';
        $fapiao['fapiao_image'] = '';
        Db::table('up_self_order')
            ->where('order_id', $order_id)
            ->update($fapiao);
        return json(['status'=>200,'msg'=>'提交成功，请耐心等待~']);
        //如果要开启自动化，把这一块注释掉就行了--end----
        $user = Db::table('up_u_user')->where('user_id', $user_id)
            ->field('user_phone')->find();
        $res = $this->askFapiaoNew($fapiao['fapiao_head'],$fapiao['fapiao_shui'],$user['user_phone'],$fapiao_email,$mingxi,$is_send['order_no'],$fapiao_remark);
        if($res['status'] == 200){
            $fapiao['fapiao_ordernum'] = $res['msg'];
            Db::table('up_self_order')
                ->where('order_id', $order_id)
                ->update($fapiao);
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }

    /**
     * 通过单号获取物流信息
     * @return \think\response\Json
     */
    public function wuliuByNumber()
    {
        extract(input());
        $wldata = orderWuLiu($number);
        $msg = $wldata['msg'];
        if($wldata['status'] != 200){
            $wldata['status'] = 100;
            $wldata['msg'] = [];
        }
        return json(['status'=>$wldata['status'],'msg'=>$msg,'wldata'=>$wldata]);
    }
}